import Game from './TwentyFortyEight'

// 创建视图
export function createView(size: number): GameView {
  const SIZE = size
  // 创建分数视图
  const scoreView = document.createElement('div')
  // 创建时间视图
  const timeView = document.createElement('div')
  // 创建网格视图
  const blocks = []
  const panelView = document.createElement('div')
  panelView.className = 'panel flex d-col main-center sub-center'
  for (let i = 0; i < SIZE; i++) {
    const row = document.createElement('div')
    const line = []
    row.className = 'row flex d-row main-between sub-center'
    for (let j = 0; j < SIZE; j++) {
      const block = document.createElement('div')
      block.className = 'block empty'
      row.appendChild(block)
      line.push(block)
    }
    panelView.appendChild(row)
    blocks.push(line)
  }
  // 创建视图容器
  const view = document.createElement('div')
  view.className = 'game'
  view.appendChild(scoreView)
  view.appendChild(timeView)
  view.appendChild(panelView)
  // 更新视图、执行动画、清空动画栈
  const update = (data: GameData) => {
    const { score, grid, animations, time } = data
    // 控制台调试
    console.log('刷新视图：')
    console.log(data)
    let gridpanel = ''
    for (let i = 0; i < SIZE; i++) {
      gridpanel += grid[i].join(' ')
      gridpanel += '\n'
    }
    console.log(gridpanel)
    // 更新分数视图
    scoreView.textContent = `分数：${score}`
    // 更新时间视图
    timeView.textContent = `时间：${time}`
    // 更新网格视图
    for (let i = 0; i < SIZE; i++) {
      for (let j = 0; j < SIZE; j++) {
        const block = blocks[i][j]
        const value = grid[i][j]
        block.className = `block ${value ? 'full' : 'empty'}`
        block.textContent = value ? value.toString() : ''
      }
    }
  }
  return { view, update }
}
